package cn.iocoder.yudao.module.handguard.job;

import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.handguard.dal.dataobject.housingresource.HousingResourceDO;
import cn.iocoder.yudao.module.handguard.dal.mysql.housingresource.HousingResourceMapper;
import com.lw.reptiles.dto.JsonResult;
import com.lw.reptiles.dto.PageData;
import com.lw.reptiles.dto.ReptilesDto;
import com.lw.reptiles.service.ReptilesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

//@Component
@Slf4j
public class ScheduledFileTasks {


    @Resource
    private HousingResourceMapper housingResourceMapper;


    //@Scheduled(cron = "30 55 23 * * ?")
    public void sysDeleteHousingImgFile() {
        //查询已标记删除数据
        LambdaQueryWrapperX<HousingResourceDO> wrapperX = new LambdaQueryWrapperX<>();
        wrapperX.eq(HousingResourceDO::getDeleted, true);
        wrapperX.eq(HousingResourceDO::getIsHutai, "0");
        List<HousingResourceDO> doList = housingResourceMapper.selectList(wrapperX);
        //deleteFiles("/usr/local/retilesImage/detailPic/","11.jpg");
        //deleteFiles("/usr/local/retilesImage/coverPic/","11.jpg");
        for (HousingResourceDO housingResourceDO : doList) {
            if (StringUtils.isNotEmpty(housingResourceDO.getDetailPic())) {
                String [] arr = housingResourceDO.getDetailPic().split(",");
                for (String s : arr) {
                    String fileName = s.replace("/detailPic/","");
                    deleteFiles("/usr/local/retilesImage/detailPic/",fileName);
                }
            }
            if (StringUtils.isNotEmpty(housingResourceDO.getCoverPic())){
                String [] arr = housingResourceDO.getCoverPic().split(",");
                for (String s : arr) {
                    String fileName = s.replace("/coverPic/","");
                    deleteFiles("/usr/local/retilesImage/coverPic/",fileName);
                }
            }
        }
    }


    public static void deleteFiles(String folderPath,String fileName) {
        // 指定文件夹路径和要删除的文件名
        // 创建File对象
        File file = new File(folderPath, fileName);

        // 检查文件是否存在
        if (file.exists()) {
            // 删除文件
            boolean isDeleted = file.delete();
            if (isDeleted) {
                System.out.println("文件已被删除");
            } else {
                System.out.println("文件删除失败");
            }
        } else {
            System.out.println("文件不存在");
        }

    }

}